<template>
	<div>
		<div class="e-m-t-45">
			<div class="flex">
				<div class="e-flex-1">
					<el-button type="primary" icon="el-icon-plus" plain @click="dialogVisible = true">新增管理员</el-button>
				</div>
				<el-form :inline="true" class="demo-form-inline">
					<el-form-item label="">
						<el-input placeholder="请输入" v-model="key" prefix-icon="el-icon-search" clearable></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="getList">查询</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<!-- 更多筛选条件 -->
		<div class="other-search-form is-active">
			<el-form label-position="left" :inline="true" size="small">
				<div class="flex align-items-center">
					<!-- <div class="e-flex-1">
						<el-form-item label="所属加盟商">
							<franchiseList v-model="innerFranchiseId" :firstSelect="true" @change="selectFranchise">
							</franchiseList>
						</el-form-item>
					</div> -->
					<div class="e-flex-1">
						<el-form-item label="员工类型">
							<el-select v-model="userType" filterable clearable placeholder="选择员工类型" @change="getList">
								<el-option
									v-for="(item,index) in userTypeList"
									:key="index"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</div>
					<div class="e-flex-1">

					</div>
				</div>
			</el-form>
		</div>
		<el-table :data="tableData" style="width: 100%" :border="true">
			<el-table-column fixed type="index" width="50">
			</el-table-column>
			<el-table-column fixed label="员工名称">
				<template slot-scope="scope">
					<div class="user-face">
						<div class="avatar">
							<el-avatar v-if="scope.row.photo" :src="fileURL + scope.row.photo" :size="40"></el-avatar>
							<el-avatar v-else :size="40">{{ scope.row.name.charAt(0) }}</el-avatar>
						</div>
						<div class="name e-p-l-15 e-p-r-5">
							{{ scope.row.name }}{{ userdetail.id == scope.row.id?'(我)':'' }}</div>
					</div>
				</template>
			</el-table-column>
			<el-table-column prop="mobile" label="手机号码" width="150">
			</el-table-column>
			<el-table-column prop="franchisename" label="所属加盟商" width="150">
				<template slot-scope="scope">
					<div v-if="scope.row.franchiselist.length > 0">
						<el-tag v-for="(item, index) in scope.row.franchiselist" :key="index" size="mini"
							class="e-m-r-10">{{item.name }}<span v-if="item.ismanager">(管理员)</span></el-tag>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="任职站点" width="300">
				<template slot-scope="scope">
					<div v-for="(item, index) in scope.row.franchiselist" :key="index">
						<span>{{ item.storelist.length }}个站点({{ item.name }})</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="是否加盟商管理员" width="150">
				<template slot-scope="scope">
					<!-- <span v-if="scope.row.brotherfranchiseid > 0">是</span>
					<span v-else>否</span> -->

					<el-switch v-model="scope.row.isfranchisemanager" @change="switchFranchisemanagerState($event, scope.row)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column label="是否小哥" width="150">
				<template slot-scope="scope">
					<!-- <span v-if="scope.row.brotherfranchiseid > 0">是</span>
					<span v-else>否</span> -->

					<el-switch v-model="scope.row.isbrother" @change="switchBrotherState($event, scope.row)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" width="300">
				<template slot-scope="scope">
					<el-button @click="views(scope.row)" type="text" size="small">查看设置</el-button>
                    <!-- <template v-if="scope.row.franchiselist.find((item)=>item.id == franchiseId)">
                        <template v-if="scope.row.franchiselist.find((item)=>item.id == franchiseId).ismanager">
                            <el-button v-if="userdetail.id != scope.row.id" type="text" @click='Remove(scope.row)'
                                size="small">
                                <span>移除管理员权限</span>
                            </el-button>
                        </template>
                    </template> -->
				</template>
			</el-table-column>
		</el-table>

		<!-- 新增管理员 -->
		<el-dialog title="新增管理员" :visible.sync="dialogVisible" width="500px">
			<el-form ref="addForm" :model="addForm" :rules="rules" label-width="140px">
				<el-form-item label="手机号码" prop="mobile">
					<autocompleteCustomer v-model="addForm.mobile" placeholder="请输入手机号码" @select="selectCustomer"
						@change="(val) => { addForm.mobile = val; addForm.userId = 0;nameDisabled = false }"
						@input="() => $refs.addForm.validateField('mobile')"
						@blur="() => $refs.addForm.validateField('mobile')">
					</autocompleteCustomer>
				</el-form-item>
				<el-form-item label="名称" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入名称" :disabled="nameDisabled"
                        @input="$refs.addForm.validateField('name')"
                        @blur="$refs.addForm.validateField('name')"></el-input>
                </el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="createUser">确定</el-button>
			</span>
		</el-dialog>

		<!-- 详情页面弹窗 -->
		<el-dialog title="员工详情" :visible.sync="viewShow.show" width="1200px">
			<clerkDetails v-if="viewShow.show" :detailsData="viewShow.detailsData" :franchiseId="franchiseId" @confirm="updateData">
			</clerkDetails>
			<span slot="footer" class="dialog-footer">
				<el-button @click="viewShow.show = false">关闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	//   import userView from './components/views.vue'
	import autocompleteCustomer from "@/components/form-select-type/autocompleteCustomer.vue"
	import customerList from '@/components/form-select-type/customerList.vue'
	import userDepartmentList from '@/components/form-select-type/userDepartmentList.vue'
	import franchiseList from '@/components/form-select-type/franchiseList.vue'
	import clerkDetails from './clerk-details.vue'
	export default {
		layout: 'admin',
		components: {
			customerList,
			userDepartmentList,
			franchiseList,
			autocompleteCustomer,
			clerkDetails
			//   userView
		},
		props: {
			franchiseId: {
				type: [Number, String],
				default: null
			}
		},
		head() {
			return {
				title: '员工列表'
			}
		},
		data() {
			// 手机号码校验规则
			const validateMobile = (rule, value, callback) => {
				if (!value) {
					callback(new Error('手机号码不能为空'));
				} else if (!/^1[3-9]\d{9}$/.test(value)) {
					callback(new Error('请输入有效的手机号码'));
				} else {
					callback();
				}
			};
			return {
				userType: 0,
				userTypeList:[
					{value:0,label:'全部'},
					// {value:1,label:'运营商管理员'},
					{value:2,label:'加盟商管理员'},
					{value:3,label:'站点管理员'},
					{value:4,label:'站点普通员工'},
					{value:7,label:'小哥'}
				],
				innerFranchiseId: null,
				viewShow: {
					id: 0,
					detailsData: {},
					show: false //详情页面弹窗
				},
				loading: true,
				key: '',
				tableData: [],
				// 新增用户
				nameDisabled: false,
				dialogVisible: false,
				addForm: {
					name: "",
					mobile: ""
				},
				rules: {
					mobile: [{
							required: true,
							validator: validateMobile,
							trigger: 'blur'
						},
						{
							min: 11,
							max: 11,
							message: '手机号码长度必须为11位',
							trigger: 'blur'
						}
					]
				},
				// 设置加盟商员工属性
				setDialogVisible: false,
				set: {
					staffId: 0,
					franchiseId: 0,
					isManager: true,
					sBrother: true,
					quota: 0
				},
			}
		},
		computed: {
			...mapState({
				userdetail: state => state.userdetail,
				operator: state => state.operator
			})
		},
		watch: {
			dialogVisible(val) {
				if (val) {
					this.addForm = {
						name: "",
						mobile: "",
					}
				}
			}
		},
		mounted() {
			// if (this.franchiseId) {
				this.innerFranchiseId = this.franchiseId
			// }
			this.getList()
		},
		methods: {
			getList() {
				this.tableData = []
				this.loading = true

				return this.$axios.post('/Select/Staff', {
					"type": this.userType,
					"franchiseId": this.innerFranchiseId || 0,
					"key": this.key
				}).then((res) => {
					this.loading = false
					let data = res
					data.forEach((item)=>{
						item.isbrother = item.brotherfranchiseid > 0?true:false
						item.isfranchisemanager = item.franchiselist.find((cell)=>cell.id == this.innerFranchiseId)?.ismanager?true:false
					})
					this.tableData = data;
				}).catch((err) => {
					this.loading = false
				})
			},
			// 设置是否加盟商管理员
			switchFranchisemanagerState(event, row){
				if(event == false){
					this.$axios.get('/Franchise/Staff/Remove', {
						params: {
							userId: row.id,
							franchiseId: this.innerFranchiseId || 0
						}
					}).then(res => {
						console.log(res)
						this.$message({
							type: 'success',
							message: '已移除加盟商管理员'
						});
					}).catch((err)=>{

						this.getList()
					})
				}else{
					this.addForm.mobile = row.mobile
					this.addForm.userId = row.id
					this.addForm.name = row.name
					
					let params = {
						mobile: this.addForm.mobile,
						userId: this.addForm.userId,
						name: this.addForm.name
					}
					if (this.franchiseId > 0) {
						params.franchiseId = this.franchiseId
					}
					this.$axios.post('/Franchise/Staff/Add', params).then((res) => {
						this.$message.success("设置管理员成功");
						this.dialogVisible = false
					}).catch(()=>{
						this.getList()
					})
				}
			},
			// 设置是否小哥
			switchBrotherState(event, row) {
				console.log('switchBrotherState', event, row)
				if(event == false){
					this.$axios.get(`/Franchise/Brother/Remove?franchiseId=${this.innerFranchiseId}&UserId=${row.id}`).then((res) => {
						console.log(res)
						this.$message({
							message: '已移除小哥',
							type: 'success'
						});
					}).catch(()=>{
						this.getList()
					})
				}else{
					let cityids = 0
					if (this.operator?.city?.cityid > 0) {
						cityids = [this.operator.city.cityid]
					}
					this.$axios.post('/Franchise/Brother/Add', {
						franchiseId: this.innerFranchiseId,
						cityids: cityids,
						quota: 0,
						mobile: row.mobile,
						UserId: row.id
					}).then((res) => {
						console.log(res)
						this.$message({
							message: '操作成功',
							type: 'success'
						});
					}).catch(()=>{
						this.getList()
					})
				}
			},
			selectCustomer(obj) {
				console.log('selectCustomer', obj)
				this.nameDisabled = true
				this.addForm.name = obj.name
				this.addForm.userId = obj.id
				this.addForm.mobile = obj.mobile
			},
			// 设置超级管理员
			setSuper(row) {
				this.$confirm('确认把该员工设为超级管理员吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$axios.get('/Franchise/Staff/SetSuper', {
						params: {
							userId: row.userid,
							franchiseId: row.franchiseid
						}
					}).then(res => {
						console.log(res)
						this.$message({
							type: 'success',
							message: '修改成功!'
						});
						this.getList()
					})
				})
			},
			chooseUser(obj) {
				console.log('chooseUser', obj)
				this.addForm.mobile = obj.mobile
				// this.addForm.userId = obj.userid
			},
			selectFranchise(val) {
				this.innerFranchiseId = val
				this.getList()
			},
			createUser() { //新增管理员
				// let params = {
				//     ...this.addForm
				// }
				let params = {
					mobile: this.addForm.mobile
				}
				if (this.addForm.userId > 0) {
					params.userId = this.addForm.userId
				} else {
					params.name = this.addForm.name
					// params.name = '手机尾号' + this.addForm.mobile.slice(-4)
				}
				if (this.franchiseId > 0) {
					params.franchiseId = this.franchiseId
				}
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$axios.post('/Franchise/Staff/Add', params).then((res) => {
							this.$message.success("新增管理员成功");
							this.dialogVisible = false
							this.getList()
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			views(row) {
				this.viewShow.detailsData = row
				this.viewShow.show = true
			},
			updateData(id) {
				console.log('updateData', id);
				this.getList().then((res) => {
					this.viewShow.detailsData = this.tableData.find((item) => item.id == id)
				})
			},
			// 移除
			// Remove(row) {
			// 	this.$confirm('确认把该员工移除管理员权限吗?', '提示', {
			// 		confirmButtonText: '确定',
			// 		cancelButtonText: '取消',
			// 		type: 'warning'
			// 	}).then(() => {
			// 		this.$axios.get('/Franchise/Staff/Remove', {
			// 			params: {
			// 				userId: row.id,
			// 				franchiseId: this.innerFranchiseId || 0
			// 			}
			// 		}).then(res => {
			// 			console.log(res)
			// 			this.$message({
			// 				type: 'success',
			// 				message: '修改成功!'
			// 			});
			// 			this.getList()
			// 		})
			// 	})
			// }
		}
	}
</script>

<style lang="scss" scoped>
	.nav-bar {
		padding: 20px 0 0;
	}

	.send {
		margin-top: 15px;
		margin-right: 10px;
	}

	.dialogForm {
		display: flex;
		flex-wrap: wrap;

		.el-form-item {
			width: 50%;
			float: left;

			&.all {
				width: 100%;
			}

			.el-select {
				width: 100%;
			}
		}
	}

	.user-face {
		display: flex;
		align-items: center;
		position: relative;

		.male,
		.female {
			font-size: 14px;
			position: absolute;
			left: 30px;
			top: 0;
			background-color: #fff;
			height: 16px;
			width: 16px;
			line-height: 16px;
			border-radius: 6px;
		}

		.male {
			color: var(--blue);
		}

		.female {
			color: var(--pink);
		}
	}
</style>